<template>
  <div id="add">
    <!-- 添加用户的对话框 -->
    <el-dialog title="添加角色" :visible.sync="dialog" :before-close="closeDialog" width="35%">
      <!-- 内容主体区域 -->
      <el-form ref="addFormRef" :rules="addFormRules" :model="addForm" label-position="right" label-width="auto" style="padding: 0 60px;">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName" />
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc" />
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">
          取消
        </el-button>
        <el-button type="primary" @click="confirmDialog">
          确定
        </el-button>
      </div>

    </el-dialog>

  </div>

</template>

<script>
export default {
  name: 'AddItem',
  props: {
    // 组件接收父级传递的控制弹框 打开/关闭的状态值
    dialog: {
      type: Boolean,
      default: null
    }
  },
  data() {
    return {
      // 添加用户的表单数据
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加表单的验证规则对象
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur'
          }
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
          { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    // 点击取消按钮，向父级传递，让父级控制对话框关闭
    closeDialog() {
      this.$emit('close')
    },
    // 点击确认，处理提交表单，向父级传递
    confirmDialog() {
      this.$refs['addFormRef'].validate((valid) => {
        if (valid) {
          // 定义一个变量为 addData 用来接收拷贝的 this.temp
          const addData = Object.assign({}, this.addForm)
          // console.log(addData)，打印看里面的字段
          this.$emit('add', addData)
        }
      })
    }
  }
}
</script>
